// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="WorkerRole.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace CloudBlitz.DeployNode.Worker
{
    using System;
    using System.Threading;

    using CloudBlitz.DeploymentManager;

    using Common;

    using Microsoft.WindowsAzure.ServiceRuntime;

    public class WorkerRole : RoleEntryPoint
    {
        private DeploymentManager deploymentManager;

        private ILogger logger;

        public override void Run()
        {
            try
            {
                var azureServiceClientsFactory = new AzureServiceClientsFactory();
                this.deploymentManager = new DeploymentManager(
                                                azureServiceClientsFactory,
                                                credentials => new SqlAzureServerManager(credentials),
                                                () => RoleEnvironment.GetLocalResource("scratch"),
                                                this.logger);

                var clusterDeploymentData = new DeploymentData
                {
                    SubscriptionId = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.SubscriptionId"),
                    ManagementCertificateThumbprint = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.ManagementCertThumbprint"),
                    ServiceCertificate = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.ServiceCertificate"),
                    StorageConnectionString = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.Storage"),
                    ClusterLocation = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.Location"),
                    ClusterDnsName = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.ClusterDnsName"),
                    AdministratorLogin = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.ClusterAdminLogin"),
                    AdministratorPassword = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.ClusterAdminPassword"),
                    ClusterTemplatePackage = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.ClusterTemplatePackage"),
                    ClusterTemplateCscfg = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.ClusterTemplateCscfg"),
                    ClusterTemplateCsdef = RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.ClusterTemplateCsdef"),
                    HeadNodeInstanceCount = int.Parse(RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.HeadNodeInstanceCount")),
                    ComputeNodeInstanceCount = int.Parse(RoleEnvironment.GetConfigurationSettingValue("CloudBlitz.ComputeNodeInstanceCount"))
                };

                this.deploymentManager.DeployCluster(clusterDeploymentData);
            }
            catch (AggregateException e)
            {
                this.logger.LogError(string.Format("An exception occured while deploying cluster: {0}", e.InnerException.ToString()));
            }
            catch (Exception e)
            {
                this.logger.LogError(string.Format("An exception occured while deploying cluster: {0}", e.ToString()));
            }

            while (true)
            {
                // Never, ever terminate the worker role... :)
                Thread.Sleep(10000);
            }
        }

        public override bool OnStart()
        {
            this.logger = Logger.Instance;

            return base.OnStart();
        }
    }
}